import axios from "@/axios"
import { loginStatus } from '@/stores/counter'


const login_status = loginStatus();

async function login(data: { account: string, password: string }): Promise<string> {
    console.log("try login: " + JSON.stringify(data));
    try {
        const response = await axios.post('/login', data);
        // 处理请求成功的响应
        console.info('Login successful:', response);
        if (response.data.success) {
            // 登录成功
            let token = response.data.data;
            initAccount(token);
            return String(token);
        } else {
            // 登陆失败
            throw response.data.msg
        }

    } catch (error) {
        // 处理登录失败的情况
        window.$utils.message.error('登录错误：' + error);
        console.error('Login error:', error);
        throw error; // 将错误抛出，以便在调用时可以捕获
    }
}


function initAccount(token: string): void {
    // 包装接口
    login_status.login(token);
}

async function register(data: { account: string, nickname: string, password: string }): Promise<string> {
    console.info("try register: " + data);
    try {
        const response = await axios.post('/register', data);
        console.log(response.data);
        // 判断是否操作成功
        if (response.data.success) {
            // 注册成功
            let token = response.data.data;
            initAccount(token);
            return String(token);
        } else {
            // 注册失败
            throw response.data.msg
        }
    } catch (error) {
        console.error('Error during POST request:', error);
        return '';
    }
}

function logout() {
    console.info("logout!");
}


export default { login, register, logout };